<!--
 * @Descripttion: 异步选择器
 * @version: 1.1
 * @Author: rookie
 * @Date: 2023年4月29日16:43:10
 * @LastEditors: rookie
 * @LastEditTime: 2023年4月29日16:43:10
-->

<template>
  <div class="net-select">
    <div v-if="data.initloading" class="net-select-loading">
      <el-icon class="is-loading"><el-icon-loading /></el-icon>
    </div>
    <el-select
      v-bind="attrs"
      :loading="data.loading"
      @visible-change="visibleChange"
    >
      <el-option
        v-for="item in data.options"
        :key="item[data.props?.value]"
        :label="item[data.props?.label]"
        :value="props.objValueType ? item : item[data.props?.value]"
      >
        <slot name="option" :data="item"></slot>
      </el-option>
    </el-select>
  </div>
</template>

<script setup>
import config from '@/config/select';
import { reactive, useAttrs } from 'vue';
const attrs = useAttrs();
const props = defineProps({
  apiObj: { type: Object, default: () => {} },
  dic: { type: String, default: '' },
  objValueType: { type: Boolean, default: false },
  params: { type: Object, default: () => ({}) },
});
const data = reactive({
  dicParams: props.params,
  loading: false,
  options: [],
  props: config.props,
  initloading: false,
});
const Initialisation = () => {
  if (hasValue()) {
    data.initloading = true;
    getRemoteData();
  }
};
//选项显示隐藏事件
const visibleChange = (ispoen) => {
  if (ispoen && data.options?.length == 0 && (props.dic || props.apiObj)) {
    getRemoteData();
  }
};
//获取数据
const getRemoteData = async () => {
  data.loading = true;
  data.dicParams[config.request.name] = props.dic;
  var res = {};
  if (props.apiObj) {
    res = await props.apiObj.get(props.params);
  } else if (props.dic) {
    res = await config.dicApiObj.get(props.params);
  }
  var response = config.parseData(res);
  data.options = response.data;
  data.loading = false;
  data.initloading = false;
};
//判断是否有回显默认值
const hasValue = () => {
  if (Array.isArray(attrs.modelValue) && attrs.modelValue.length <= 0) {
    return false;
  } else if (attrs.modelValue) {
    return true;
  } else {
    return false;
  }
};
Initialisation();
</script>

<style scoped>
.net-select {
  display: inline-block;
  position: relative;
}
.net-select-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  z-index: 100;
  border-radius: 5px;
  border: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  padding-left: 10px;
}
.net-select-loading i {
  font-size: 14px;
}

.dark .net-select-loading {
  background: var(--el-bg-color-overlay);
  border-color: var(--el-border-color-light);
}
</style>
